package com.edu.weixin.service.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.edu.weixin.common.ImageMessage;
import com.edu.weixin.common.InputMessage;
import com.edu.weixin.common.OutputMessage;
import com.edu.weixin.constant.MsgType;
import com.edu.weixin.service.AbstractMessage;
import com.edu.weixin.service.MessageService;
import com.edu.weixin.service.TuLingService;
import com.thoughtworks.xstream.XStream;

@Service
public class MessageServiceImpl extends AbstractMessage implements MessageService {
	Logger logger = Logger.getLogger(MessageServiceImpl.class);

	@Autowired
	private TuLingService tlService;

	/**
	 * 接收消息(文本/图片)
	 * 
	 * @param request
	 * @param response
	 */
	public void acceptMessage(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			XStream xs = getXStreamForReq(request);
			InputMessage inputMsg = getInputMessageForReq(request, xs);

			String msgType = inputMsg.getMsgType();
			String servername = inputMsg.getToUserName();
			String custermname = inputMsg.getFromUserName();
			long createTime = inputMsg.getCreateTime();
			long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;

			logger.info("开发者微信号：" + servername + ";发送方帐号：" + custermname);
			logger.info("消息创建时间：" + inputMsg.getCreateTime() + new Date(createTime * 1000l));

			String str = "";
			if (MsgType.TEXT.equals(msgType)) {
				if (MsgType.TEXT.equals(msgType)) {
					JSONObject tuLingReplyJson = tlService.tuLingReplyMsg(inputMsg.getContent());

					String code = tuLingReplyJson.get("code").toString();

					if (MsgType.TULINGCODE_LINK.equals(code)) {

					} else if (MsgType.TULINGCODE_NEWS.equals(code)) {
						//acceptMessageNews(inputMsg, xs, custermname, servername, createTime,tuLingReplyJson.get("text").toString());
					} else if (MsgType.TULINGCODE_TEXT_FLIGHT.equals(code)) {

					} else if (MsgType.TULINGCODE_TEXT_MENU.equals(code)) {

					} else if (MsgType.TULINGCODE_TEXT_TRAIN.equals(code)) {

					} else {
						str = acceptMessageByText(xs, custermname, servername, returnTime,tuLingReplyJson.get("text").toString());
					}

					logger.info("消息内容：" + inputMsg.getContent() + "；消息Id：" + inputMsg.getMsgId());

				} else if (MsgType.IMAGE.equals(msgType)) {
					str = acceptMessageByImage(inputMsg, xs, custermname, servername, returnTime);
				}
				
				logger.info("消息内容：" + inputMsg.getContent() + "；消息Id：" + inputMsg.getMsgId());

			} else if (MsgType.IMAGE.equals(msgType)) {
				str = acceptMessageByImage(inputMsg, xs, custermname, servername, returnTime);
			}
			logger.info("xml内容：" + str);
			out = response.getWriter();
			out.write(str);

		} catch (IOException e) {
			e.printStackTrace();
		}
		if (out != null) {
			out.close();
		}

		out = null;
	}

	/**
	 * 返回文本消息
	 * 
	 * @param custermname
	 * @param servername
	 * @param returnTime
	 * @param content
	 * @return
	 */
	private String acceptMessageByText(XStream xs, String custermname, String servername,
			long returnTime, String content) {
		InputMessage outputMsg = new InputMessage();
		outputMsg.setFromUserName(servername);
		outputMsg.setToUserName(custermname);
		outputMsg.setCreateTime(returnTime);
		outputMsg.setMsgType(MsgType.TEXT);
		outputMsg.setContent(content);
		return xs.toXML(outputMsg);
	}

	/**
	 * 返回图片信息
	 * 
	 * @param inputMsg
	 * @param xs
	 * @param custermname
	 * @param servername
	 * @param returnTime
	 * @return
	 */
	private String acceptMessageByImage(InputMessage inputMsg, XStream xs, String custermname,
			String servername, long returnTime) {
		logger.info("获取多媒体信息");
		logger.info("多媒体文件id：" + inputMsg.getMediaId() + ";图片链接：" + inputMsg.getPicUrl()
				+ "消息id，64位整型：" + inputMsg.getMsgId());
		OutputMessage outputMsg = new OutputMessage();
		outputMsg.setFromUserName(servername);
		outputMsg.setToUserName(custermname);
		outputMsg.setCreateTime(returnTime);
		outputMsg.setMsgType(MsgType.IMAGE);
		ImageMessage images = new ImageMessage();
		images.setMediaId(inputMsg.getMediaId());
		outputMsg.setImage(images);
		return xs.toXML(outputMsg);
	}

	private String acceptMessageNews(InputMessage inputMsg, XStream xs, String custermname,
			String servername, long createTime, int articleCount) {
		OutputMessage outputMsg = new OutputMessage();
		outputMsg.setFromUserName(servername);
		outputMsg.setToUserName(custermname);
		outputMsg.setCreateTime(createTime);
		outputMsg.setMsgType(MsgType.NEWS);
		return "";
	}
}
